
import 'dart:io';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

import 'bean/books_bean.dart';

class DBUtil{
  DBUtil._();
  static final DBUtil dbUtil=DBUtil._();
  Database _database;
  //获取database对象
  Future<Database> get database async{
    if(_database!=null){
      return _database;
    }
    _database = await initDB();
    return _database;
  }
  initDB() async{
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'book_reading.db');
    return await openDatabase(path,version: 1,onOpen: (db){},
      onCreate: (Database db,int version) async{
      await db.execute('''CREATE TABLE user_like_books (id INTEGER PRIMARY KEY, 
        book_name TEXT,
        book_url TEXT,
        book_cover TEXT,
        book_detail_bean TEXT,
        reading_chapter TEXT)''');
      }
    );
  }
  
  insertBook(String bookName,String bookUrl,String bookCover,String bookDetailJson,String readingChapter) async{
    final db= await database;
//    var table = await db.rawQuery('SELECT MAX(id)+1 as id FROM user_like_books');
//    int id= table.first['id'];
    var raw = await db.rawInsert(
        'INSERT INTO user_like_books(book_name, book_url, book_cover, book_detail_bean, reading_chapter) VALUES(?, ?, ?, ?, ?)',
      [bookName,bookUrl,bookCover,bookDetailJson,readingChapter]
    );
    return raw;
  }

  updateBook(String bookName,String readingChapter) async{
    final db = await database;
    var raw = await db.rawUpdate('UPDATE user_like_books SET reading_chapter = ? WHERE book_name = ?',
        [readingChapter, bookName]);
    return raw;
  }

  Future<List<DBHelpFavoriteBean>> getAllBook() async{
    final db = await database;
    var res=await db.query('user_like_books');
    List<DBHelpFavoriteBean> list=res.isNotEmpty ? res.map((c)=> DBHelpFavoriteBean.fromMap(c)).toList():[];
    return list;
  }

  deleteBook(String bookName) async{
    final db = await database;
    return db.delete('user_like_books',where: 'book_name = ?',whereArgs: [bookName]);
  }
  Future<bool> haveBook(String bookName) async{
    final db = await database;
    var res = await db.query('user_like_books',where: 'book_name = ?',whereArgs: [bookName]);
    return res.isNotEmpty?true:false;
  }
}